<script setup>
import { reactive, ref } from 'vue';
import router from '@/router';
import loginApi from '@/api/loginApi.js';
import { Expand, Fold, Stamp, SwitchButton, Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import UserApi from "@/api/userApi.js";

const activeIndex = ref('1')
const editWinVisible = ref(false);
const unkonwnVisible = ref(false);
// 取出当前登录用户的信息
const loginAdmin = ref({
  id: "",
  username: "",
  realName: "",
  idCard: "",
  sex: "",
  phone: "",
  role: "",
  imgUrl: "",
  newPassword: "",
  confirmPassword: '',
  oldPassword: '',
  email: "",
  emailCaptcha: "",
});

// 修改信息表单
const editForm = ref({
  id: "",
  username: "",
  realName: "",
  idCard: "",
  sex: "",
  phone: "",
  role: "",
  imgUrl: "",
});

const dialogVisible = ref(false);
const imageUrl = ref('');

getLogin();

// 菜单  用户管理， 分类管理， 商品管理
const menuData = ref([]);

// 普通用户菜单
const regularUserMenu = [
  {name: '票务业务', icon: 'Tickets', children: [
      {name: '查询车票', icon: 'Search',path: "/ticket"},
    ]},
  {name: '订单管理', icon: 'Document', children: [
      {name: '待支付订单', icon: 'Warning',path: "/uncommit"},
      {name: '已完成订单', icon: 'DocumentChecked',path: "/commit"},
      {name: '剩余车票可视化展示', icon: 'PieChart',path: "/pieChart"},
      {name: '实时地图规划', icon: 'MapLocation',path: "/mapContainer"},
      // {name: '退票改签审核', icon: 'UserFilled',path: "/ticket"},
    ]},
];

// 管理员菜单
const adminMenu = [
  {name: '管理员管理', icon: 'Setting', children: [
      {name: '车站管理', icon: 'OfficeBuilding',path: "/station"},
      {name: '列车管理', icon: 'Van',path: "/train"},
      {name: '线路管理', icon: 'Guide',path: "/trainRoute"},
      {name: '班次管理', icon: 'Calendar',path: "/schedule"},
      {name: '用户管理', icon: 'User',path: "/user"},
      {name: '订单管理', icon: 'Document',path: "/finish"},
    ]},
  // {name: '订单业务管理', icon: 'GobletFull', children: [
  //     {name: '订单查询', icon: 'GobletSquareFull', path: "/sqlTicket"},
  //     {name: '退票审核', icon: 'TrendCharts', path: "/charts"},
  //     {name: '票据统计', icon: 'TrendCharts', path: "/charts"},
  //   ]},
  // {name: '用户信息管理', icon: 'Notebook', children: [
  //     {name: '用户界面', icon: 'Document', path: "/course"},
  //   ]},
  // {name: '管理员管理', icon: 'User', children: [
  //     {name: '列车安排', icon: 'UserFilled', path: "/member"},
  //     {name: '线路安排', icon: 'UserFilled', path: "/member"},
  //     {name: '车站安排', icon: 'UserFilled', path: "/member"},
  //   ]},
];

// 获取认证头部信息
const getAuthHeaders = () => {
  try {
    if (typeof window !== 'undefined' && window.localStorage) {
      const token = localStorage.getItem('token');
      console.log('获取到的token:', token); // 调试用
      if (token) {
        // // 确保token格式正确
        // const trimmedToken = token.trim();
        return { Authorization: token };
      }
    }
  } catch (error) {
    console.error('获取token时出错:', error);
  }
  return {};
};


async function getLogin() {
  let token = localStorage.getItem("token");
  if (!token) {
    //没token跳转登陆页面
    router.push("/login");
  }
  //获取用户信息
  const res = await loginApi.getloginbean();
  console.log(res);
  loginAdmin.value = res;

  // 根据用户角色设置菜单
  if (loginAdmin.value.role == 'REGULAR_USER') {
    menuData.value = regularUserMenu;
  } else if (loginAdmin.value.role == 'ADMIN') {
    menuData.value = adminMenu;
  } else {
    // 默认菜单或空菜单
    menuData.value = [];
  }
}

// 用户下拉菜单的点击
function handleSelect(key, keyPath) {
  if (key == 'logout') {
    // 用户退出
    logout();
  }
  else if (key == 'edit') {
    // 修改信息
    openEditDialog();
  }
  if (key == 'updatePassword') {
    // 重置密码
    updatePassword();
  }
}

// 打开修改信息弹窗
function openEditDialog() {
  // 初始化表单数据
  editForm.value = {
    id: loginAdmin.value.id,
    username: loginAdmin.value.username,
    realName: loginAdmin.value.realName,
    idCard: loginAdmin.value.idCard,
    sex: loginAdmin.value.sex,
    phone: loginAdmin.value.phone,
    role: loginAdmin.value.role,
    imgUrl: loginAdmin.value.imgUrl,
    email: loginAdmin.value.email,
  };
  // 设置头像URL（如果有）
  imageUrl.value = loginAdmin.value.imgUrl || '';
  dialogVisible.value = true;
}

// 左侧菜单动作
function handleMenu(key) {
  if (key) {
    router.push(key);
  }
}

// 退出
function logout() {
  // 清除Token
  localStorage.removeItem("token")
  // 跳转到登录
  router.push('/login')
}

//重置密码
function updatePassword() {
  editWinVisible.value = true;
}




// 头像上传成功处理
const handleAvatarSuccess = (response, file, fileList) => {
  // 根据后端实际返回的数据结构调整这里的代码
  console.log('上传成功:', response)
  editForm.value.imgUrl = response.data;
  // 同时更新 imageUrl 用于预览显示
  imageUrl.value = response.data;
  ElMessage.success('头像上传成功');
}

// 头像上传前处理
const beforeAvatarUpload = (rawFile) => {
  // 检查是否有有效的token
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.error('未登录或登录已过期，请重新登录');
    router.push('/login');
    return false;
  }

  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('头像图片必须是 JPG 或 PNG 格式!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像图片大小不能超过 2MB!');
    return false;
  }
  return true;
}

// 保存修改信息
const saveEdit = async () => {
  try {
    // 这里调用保存用户信息的API
    await UserApi.edit(editForm.value);
    ElMessage.success('信息修改成功');
    dialogVisible.value = false;

    // 更新本地用户信息
    Object.assign(loginAdmin.value, editForm.value);

    // 如果有新头像，也更新头像
    if (imageUrl.value) {
      loginAdmin.value.imgUrl = imageUrl.value;
    }

  } catch (error) {
    ElMessage.error('信息修改失败');
  }
}
//忘记密码
const unknown = () => {
  loginAdmin.value.newPassword ="";//清空数据
  loginAdmin.value.confirmPassword = "";//清空数据
  loginAdmin.value.emailCaptcha = "";
  editWinVisible.value = false;//关闭对话框
  unkonwnVisible.value = true;//打开忘记密码对话框
}
//忘记密码返回
const unknowCancel = () => {
  loginAdmin.value.email = "";//清空数据
  unkonwnVisible.value = false;//关闭忘记密码对话框
  editWinVisible.value = true;//打开对话框
}
//忘记密码获取验证码
const getCaptcha = () => {
  const unknownData = {
      email: loginAdmin.value.email
  }
  UserApi.getUnknownCommit(unknownData);
}
//忘记密码提交验证码
const unknownCommit = async() => {
  if(loginAdmin.value.newPassword!=loginAdmin.value.confirmPassword){
    ElMessage.error('密码不一致');
    loginAdmin.value.confirmPassword = "";//清空数据
    loginAdmin.value.newPassword = "";//清空数据
    return;
  }
  // 创建密码数据对象
  const passwordData = {
    newPassword: loginAdmin.value.newPassword,
    emailCaptcha: loginAdmin.value.emailCaptcha,
    email: loginAdmin.value.email
  };
  try {
    var newVar = await UserApi.unknownUpdatePassword(passwordData);
    if(newVar){
      ElMessage.success('密码修改成功');
      loginAdmin.value.newPassword = '';
      loginAdmin.value.confirmPassword = '';
      loginAdmin.value.emailCaptcha = '';
      unkonwnVisible.value = false;//关闭对话框
      logout();
    }
  } catch (error) {
    ElMessage.error('密码修改失败');
  }

}


//取消修改操作
const editCancel = () => {
  loginAdmin.value.newPassword ="";//清空数据
  loginAdmin.value.confirmPassword = "";//清空数据
  editWinVisible.value = false;//关闭对话框
}
//修改提交
const editCommit = async () => {
  if(loginAdmin.value.newPassword!=loginAdmin.value.confirmPassword){
    ElMessage.error('密码不一致');
    loginAdmin.value.confirmPassword = "";//清空数据
    loginAdmin.value.newPassword = "";//清空数据
    return;
  }
  // 创建密码数据对象
  const passwordData = {
    oldPassword: loginAdmin.value.oldPassword,
    newPassword: loginAdmin.value.newPassword
  };
  try {
    var newVar = await UserApi.updatePassword(passwordData);
    if(newVar)
    ElMessage.success('密码修改成功');
    loginAdmin.value.newPassword = '';
    loginAdmin.value.confirmPassword = '';
    loginAdmin.value.oldPassword = '';
    editWinVisible.value = false;//关闭对话框
    logout();
  } catch (error) {
    ElMessage.error('密码修改失败');
  }
}

// 左侧菜单展开折叠
const isCollapse = ref(false);
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-menu :default-active="activeIndex"
                 class="el-menu-demo"
                 mode="horizontal"
                 :ellipsis="false"
                 background-color="#f3f7ff"
                 text-color="#393939"
                 active-text-color="#ffd04b"
                 @select="handleSelect">
          <el-menu-item index="0">
            <img style="height: 80%" src="@/img/logo.png" alt="票游假期-----火车票订票管理系统"/>
            <span style="padding-left: 50px; font-size: 24px; color:#393939;">票游假期-----火车票订票管理系统</span>
          </el-menu-item>
          <div class="flex-grow"/>
          <el-sub-menu index="1">
            <template #title>
              <img
                  v-if="loginAdmin && loginAdmin.imgUrl"
                  :src="loginAdmin.imgUrl"
                  class="user-avatar"
                  alt="头像"
                  style="width: 40px; height: 40px; border-radius: 50%;"
              />
              <el-icon>
                <Stamp></Stamp>
              </el-icon>
              {{ loginAdmin ? loginAdmin.username : '没登录' }}
            </template>
            <el-menu-item index="edit">修改信息</el-menu-item>
            <el-menu-item index="updatePassword">重置密码</el-menu-item>
            <el-menu-item index="logout">退出
              <el-icon>
                <SwitchButton></SwitchButton>
              </el-icon>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-header>
      <el-container>
        <el-aside :width="1">
          <div
              style="height: 60px;line-height: 60px; text-align: right; color: #FFF; font-size: 20px; margin-right: 24px;">
            <el-icon @click="isCollapse=!isCollapse">
              <Expand v-if="isCollapse"></Expand>
              <Fold v-else></Fold>
            </el-icon>
          </div>
          <el-menu active-text-color="#ffd04b" background-color="#0c1d40" class="el-menu-vertical-demo"
                   default-active="/charts" text-color="#fff" :collapse="isCollapse"
                   @select="handleMenu">
            <!-- 动态生成菜单 -->
            <el-sub-menu v-for="(menu, index) in menuData" :key="index" :index="index.toString()">
              <template #title>
                <component
                    class="icons"
                    :is="menu.icon"
                    style="width: 1em; height: 1em; margin-right: 8px">
                </component>
                <span>{{ menu.name }}</span>
              </template>
              <el-menu-item v-for="(child, ind) in menu.children" :key="ind" :index="child.path">
                <el-icon>
                  <component
                      :is="child.icon">
                  </component>
                </el-icon>
                <span>{{ child.name }}</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>

    <!-- 修改信息弹窗 -->
    <el-dialog v-model="dialogVisible" title="修改个人信息" width="500px">
      <el-form :model="editForm" label-width="80px">
        <div style="text-align: center; margin-bottom: 20px;">
          <el-upload
              class="avatar-uploader"
              action="/api/login/img"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="getAuthHeaders()"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
<!--            <img v-else src="@/img/123.png" class="avatar" />-->
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div style="margin-top: 10px; color: #999;">点击上传头像</div>
        </div>

        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="真实姓名">
          <el-input v-model="editForm.realName"></el-input>
        </el-form-item>

        <el-form-item label="身份证号">
          <el-input v-model="editForm.idCard"></el-input>
        </el-form-item>

        <el-form-item label="性别">
          <el-select v-model="editForm.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="手机号">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>


      </el-form>


      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>



  <!--重置密码表单-->
  <el-dialog v-model="editWinVisible" title="编辑" width="500">
    <el-form :model="loginAdmin">
      <el-form-item label="请输入旧密码" :label-width="100">
        <el-input v-model="loginAdmin.oldPassword" autocomplete="off" />
      </el-form-item>
      <el-form-item label="请输入新密码" :label-width="100">
        <el-input v-model="loginAdmin.newPassword" autocomplete="off" />
      </el-form-item>
      <el-form-item label="请再次输入新密码" :label-width="100">
        <el-input v-model="loginAdmin.confirmPassword" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="unknown">忘记密码</el-button>
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--忘记密码表单-->
  <el-dialog v-model="unkonwnVisible" title="编辑" width="500">
    <el-form :model="loginAdmin">
      <el-form-item label="邮箱号" :label-width="100">
        <el-input v-model="loginAdmin.email" autocomplete="off" disabled />
      </el-form-item>
      <el-form-item label="请输入验证码" :label-width="100">
        <el-input v-model="loginAdmin.emailCaptcha" autocomplete="off" />
      </el-form-item>
      <el-form-item label="请输入新密码" :label-width="100">
        <el-input v-model="loginAdmin.newPassword" autocomplete="off" />
      </el-form-item>
      <el-form-item label="请再次输入新密码" :label-width="100">
        <el-input v-model="loginAdmin.confirmPassword" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="unknowCancel">返回</el-button>
        <el-button type="primary" @click="getCaptcha">
          获取验证码
        </el-button>
        <el-button @click="unknownCommit">提交</el-button>
      </div>
    </template>
  </el-dialog>






</template>

<style scoped>
.flex-grow {
  flex-grow: 1;
}

.common-layout,
.el-container {
  height: 100%;
}

.el-header {
  --el-header-padding: 0;
  --el-header-height: 80px;
  box-sizing: border-box;
  flex-shrink: 0;
  height: var(--el-header-height);
  padding: var(--el-header-padding);
}

.el-menu--horizontal {
  height: 80px;
}

.el-aside {
  background-color: #0c1d40;
}

.el-main {
  padding: 0px;
}

.el-menu {
  border-width: 0px;
}

.el-menu-item {
  font-size: 16px;
}

.el-menu-demo {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.25);
}

.el-sub-menu__title {
  font-size: 16px;
}

/* 头像上传样式 */
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  margin: 0 auto;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}


.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}
</style>
